/**
 *******************************************************************************
 * @file      cppm_driver.c
 * @version   V1.0.0    
 * @date      2013.05.04
 * @brief     pxx pulse driver for Tananis on PA7.	
 *            Resources: 
 *                 TIM8_UP
 *                 DMA2_Stream1, channel 7
 *            By writing, the data stream is converted into Cppm pulses,
 *
 *******************************************************************************
 * @author    - Adela 
 *            - Robert Zhang <armner@gmail.com>
 *            - 
 *
 */

#include "stm32f2xx.h"
#include "cppm_driver.h"
#include "interrupt.h"
#include "FreeRTOS.h"
#include "semphr.h"

static xSemaphoreHandle cppm_sema=NULL;
static uint16_t cppm_stream[32]={1600,1600,1600,1600,1600,1600,1600};
static unsigned char cppm_len;

void DMA2_Stream1_IRQHandler_cppm();


int cppm_open(Driver *driver)
{
    GPIO_InitTypeDef GPIO_InitStructure;

    RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);

    GPIO_PinAFConfig(GPIOA, GPIO_PinSource7, GPIO_AF_TIM8);

    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_7;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
    GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
    GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
    GPIO_Init(GPIOA, &GPIO_InitStructure);

    //create a flag for waiting
     vSemaphoreCreateBinary(cppm_sema);
    if(cppm_sema ==NULL)
    {
        return -1;
    }
    
    DMA2_Stream1_Interrupt_Handler =DMA2_Stream1_IRQHandler_cppm;
    
    //get system clocks
    RCC_ClocksTypeDef RCC_Clocks;
        
    RCC_GetClocksFreq( &RCC_Clocks);
    
    RCC->APB2ENR |= RCC_APB2ENR_TIM8EN ;            // Enable clock
    RCC->AHB1ENR |= RCC_AHB1ENR_DMA2EN ;            // Enable DMA2 clock

    DMA_InitTypeDef DMA_InitStructure;

    DMA_DeInit(DMA2_Stream1);
    DMA_InitStructure.DMA_Channel = DMA_Channel_7;  
    DMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t)&(TIM8->ARR) ;
    DMA_InitStructure.DMA_Memory0BaseAddr = (uint32_t)cppm_stream;
    DMA_InitStructure.DMA_DIR = DMA_DIR_MemoryToPeripheral;
    DMA_InitStructure.DMA_BufferSize = 4;
    DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable;
    DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Enable;
    DMA_InitStructure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_HalfWord;
    DMA_InitStructure.DMA_MemoryDataSize = DMA_PeripheralDataSize_HalfWord;
    DMA_InitStructure.DMA_Mode = DMA_Mode_Normal;
    DMA_InitStructure.DMA_Priority = DMA_Priority_VeryHigh;
    DMA_InitStructure.DMA_FIFOMode = DMA_FIFOMode_Disable;
    DMA_InitStructure.DMA_FIFOThreshold = DMA_FIFOThreshold_Full;
    DMA_InitStructure.DMA_MemoryBurst = DMA_MemoryBurst_Single;
    DMA_InitStructure.DMA_PeripheralBurst = DMA_PeripheralBurst_Single;

    DMA_Init(DMA2_Stream1, &DMA_InitStructure);

    //config TIM1 as 9ms pulse driver
    TIM_TimeBaseInitTypeDef  TIM_TimeBaseStructure;
    TIM_OCInitTypeDef  TIM_OCInitStructure;    

    /* Time Base configuration */
    TIM_TimeBaseStructure.TIM_Prescaler = (RCC_Clocks.PCLK2_Frequency*2) / 1500000 - 1 ;
    TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
    TIM_TimeBaseStructure.TIM_Period = 0xFFFF;
    TIM_TimeBaseStructure.TIM_ClockDivision = 0;
    TIM_TimeBaseStructure.TIM_RepetitionCounter = 0;

    TIM_TimeBaseInit(TIM8, &TIM_TimeBaseStructure);

    /* Channel 1 Configuration in PWM mode */
    TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
    TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
    TIM_OCInitStructure.TIM_OutputNState = TIM_OutputNState_Enable;
    TIM_OCInitStructure.TIM_Pulse = 600;
    TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low;
    TIM_OCInitStructure.TIM_OCNPolarity = TIM_OCNPolarity_Low;
    TIM_OCInitStructure.TIM_OCIdleState = TIM_OCIdleState_Set;
    TIM_OCInitStructure.TIM_OCNIdleState = TIM_OCNIdleState_Set;

    TIM_OC1Init(TIM8, &TIM_OCInitStructure);
    
    /* DMA enable*/
    DMA_Cmd(DMA2_Stream1, ENABLE);
    DMA_ITConfig(DMA2_Stream1,DMA_IT_TC,ENABLE);
    
    TIM_DMAConfig(TIM8, TIM_DMABase_ARR, TIM_DMABurstLength_1Transfer);
    TIM_DMACmd(TIM8, TIM_DMA_Update, ENABLE);

    /* Main Output Enable */
    TIM_CtrlPWMOutputs(TIM8, ENABLE);

    /* TIM1 counter enable */
    //TIM_Cmd(TIM8, ENABLE);
  
    NVIC_EnableIRQ(DMA2_Stream1_IRQn) ;
    
    return 0;
}

int cppm_write(Driver *driver, void *buffer, int len, OFFSET offset)
{
    uint16_t *p_short;
    uint16_t total_cppm_len;
    int i;
    
    if( (len) > sizeof(cppm_stream)) return -1;
    cppm_len = (len>>1) +1;
    
    DMA_ITConfig(DMA2_Stream1,DMA_IT_TC,DISABLE);

   
    p_short =buffer;
    total_cppm_len=0;
    for(i=0; i<cppm_len-1; i++)
    {
        total_cppm_len +=*p_short;
        cppm_stream[i] = *p_short++;
    }

    cppm_stream[cppm_len-1] =15*2000 -total_cppm_len;

    DMA_ITConfig(DMA2_Stream1,DMA_IT_TC,ENABLE);

    TIM_Cmd(TIM8, ENABLE);
    return 0;
}

int cppm_read(Driver *driver, void *buffer, int len, OFFSET offset)
{
    xSemaphoreTake(cppm_sema, portMAX_DELAY);
    return 0;
}

void DMA2_Stream1_IRQHandler_cppm()
{
    if(DMA_GetITStatus(DMA2_Stream1, DMA_IT_TCIF1))
    {
        static signed portBASE_TYPE xHigherPriorityTaskWoken;
        xHigherPriorityTaskWoken =pdFALSE;
		
        DMA_ClearITPendingBit(DMA2_Stream1, DMA_IT_TCIF1);  
    
        xSemaphoreGiveFromISR(cppm_sema, &xHigherPriorityTaskWoken);
    }
    else
    {
        return;
    }
    if(0){
        #include "led_driver.h"
        static char t;

        t^=1;
        led_driver.write(&led_driver,&t,sizeof(t),0);
    }
    
    //fire DMA
    DMA_InitTypeDef DMA_InitStructure;

    DMA_DeInit(DMA2_Stream1);
    DMA_InitStructure.DMA_Channel = DMA_Channel_7;  
    DMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t)&(TIM8->ARR) ;
    DMA_InitStructure.DMA_Memory0BaseAddr = (uint32_t)cppm_stream;
    DMA_InitStructure.DMA_DIR = DMA_DIR_MemoryToPeripheral;
    DMA_InitStructure.DMA_BufferSize = cppm_len;
    DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable;
    DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Enable;
    DMA_InitStructure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_HalfWord;
    DMA_InitStructure.DMA_MemoryDataSize = DMA_PeripheralDataSize_HalfWord;
    DMA_InitStructure.DMA_Mode = DMA_Mode_Normal;
    DMA_InitStructure.DMA_Priority = DMA_Priority_VeryHigh;
    DMA_InitStructure.DMA_FIFOMode = DMA_FIFOMode_Disable;
    DMA_InitStructure.DMA_FIFOThreshold = DMA_FIFOThreshold_Full;
    DMA_InitStructure.DMA_MemoryBurst = DMA_MemoryBurst_Single;
    DMA_InitStructure.DMA_PeripheralBurst = DMA_PeripheralBurst_Single;

    DMA_Init(DMA2_Stream1, &DMA_InitStructure);

    DMA_Cmd(DMA2_Stream1, ENABLE);
    DMA_ITConfig(DMA2_Stream1,DMA_IT_TC,ENABLE);
}

int cppm_close(Driver *driver)
{
    GPIO_InitTypeDef GPIO_InitStructure;

    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_7;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
    GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
    GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
    GPIO_Init(GPIOA, &GPIO_InitStructure);
 
    DMA_DeInit(DMA2_Stream1);
    TIM_DeInit(TIM8);
    
    NVIC_DisableIRQ(DMA2_Stream1_IRQn) ;
    
    vSemaphoreDelete(cppm_sema);
    return 0;
}

Driver cppm_driver =
{
    &cppm_open,
    &cppm_write,
    &cppm_read,
    NULL,
    &cppm_close
};




